var fs = require('fs')
var Inform = require('../handlers/informHandler')
var Spit = require('../handlers/spitHandler')


var illegalArr = []

module.exports = function (io) {

  io.of('/inform').on('connection', function (socket) {

    Inform.find({}, function (err, informs) {
      if (!err) {
        socket.emit('inform list', {list: informs.reverse()})
      }
    })

    socket.on('new inform', function (data) {
      Inform.insert(data, function (err) {
        if (!err) {
          socket.broadcast.emit('new inform', data)
        }
      })
    })

  })

  io.of('/spit').on('connection', function (socket) {

    Spit.find({}, function (err, spits) {
      if (!err) {
        spits.sort(function (obj1, obj2) {
          return new Date(obj1.createdAt) - new Date(obj2.createdAt)
        })
        socket.emit('spit list', {list: spits})
      }
    })

    socket.on('new spit', function (data) {
      if (illegalArr.indexOf(data.handler.name) > -1) {
        socket.emit('stop spit', {msg: '禁言期间不能发言'})
      } else {
        if (data.handler.id == -1) {
          data.createdAt = new Date()
          socket.emit('new spit', data)
          socket.broadcast.emit('new spit', data)
        } else {
          Spit.insert(data, function (err) {
            socket.emit('new spit', data)
            socket.broadcast.emit('new spit', data)
          })
        }
        
      }
    })

    socket.on('illegal', function (data) {
      var handler = data.handler
      if (illegalArr.indexOf(handler.name) == -1) {
        illegalArr.push(handler.name)
        data = {inform: handler.name + '试图发送违规内容，被系统禁言1分钟', createdAt: new Date()}
     
        socket.emit('new spit', data)
        socket.broadcast.emit('new spit', data)
        setTimeout(function () {
          illegalArr = illegalArr.filter(function(item) {
            return item != handler.name
          })
        }, 60000)
      }
      

    })

  })
}